<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <!--            网站标签模块-->
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img src="../assets/logo.jpg" alt="logo" class="logo" />
            <div class="title">胡图图库</div>
          </div>
        </RouterLink>
      </a-col>
      <!--            导航栏模块-->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
      <!--          用户头像模块-->
      <a-col flex="120px">
        <a-dropdown>
          <ASpace>
            <div v-if="loginUserStore.loginUser.id">
              <a-avatar :src="loginUserStore.loginUser.userAvatar" />
              {{ loginUserStore.loginUser.userName ?? '无名' }}
            </div>
            <div v-else>
              <a-button type="primary" href="/user/login">登录</a-button>
            </div>
          </ASpace>
          <template #overlay v-if="loginUserStore.loginUser.id">
            <a-menu>
              <a-menu-item>
                <router-link to="/my_info">
                  <UserOutlined />
                  个人信息
                </router-link>
              </a-menu-item>
              <a-menu-item>
                <router-link to="/my_space">
                  <RobotOutlined />
                  个人空间
                </router-link>
              </a-menu-item>
              <a-menu-item @click="doLogout">
                <LogoutOutlined />
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref } from 'vue'
import {
  BankOutlined,
  ContactsOutlined,
  HomeOutlined,
  LogoutOutlined,
  PictureOutlined,
  PlusCircleOutlined,
  RedditOutlined,
  RobotOutlined,
  TwitterOutlined,
  UserOutlined,
  FieldTimeOutlined
} from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { userLogoutUsingPost } from '@/api/userController'

const loginUserStore = useLoginUserStore()

const router = useRouter() //获取路由对象
// 监听路由变化，更新当前选中菜单
const current = ref<string[]>([])
router.afterEach((to, from, next) => {
  current.value = [to.path]
})
//点击菜单栏跳转对应路径函数
const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

/**
 * 用户注销
 */
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  console.log(res)
  // 如果注销，跳转到登录页面
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败' + res.data.message)
  }
}

/**
 * 菜单项逻辑
 */
//原始菜单列表
const originItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  {
    key: '/add_picture',
    icon: () => h(PlusCircleOutlined),
    label: '创建图片',
    title: '创建图片',
  },
  {
    key: '/admin/userManage',
    icon: () => h(ContactsOutlined),
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: '/admin/pictureManage',
    icon: () => h(PictureOutlined),
    label: '图片管理',
    title: '图片管理',
  },
  {
    key: '/admin/spaceManage',
    icon: () => h(BankOutlined),
    label: '空间管理',
    title: '空间管理',
  },
  {
    key: '/timeline',
    icon: () => h(FieldTimeOutlined),
    label: '时间线',
    title: '时间线',
  },
  {
    key: 'more',
    label: '更多项目',
    title: '更多项目',
    children: [
      {
        type: 'group',
        label: '欢迎体验',
        children: [
          {
            title: '奇遇旅途',
            label: h(
              'a',
              { href: 'http://www.trip.qiyuya.top/#/home', target: '_blank' },
              '奇遇旅途',
            ),
            key: 'qiyu-trip',
            icon: () => h(TwitterOutlined),
          },
          {
            title: 'tomago-代码生成',
            label: h(
              'a',
              { href: 'https://www.toma.qiyuya.top/', target: '_blank' },
              'tomago-代码生成',
            ),
            key: 'tomago',
            icon: () => h(RedditOutlined),
          },
        ],
      },
    ],
  },
  {
    key: 'mywebsite',
    label: h('a', { href: 'https://wangziqi.rth1.xyz/', target: '_blank' }, '个人网站'),
    title: '个人网站',
    children: [
      {
        type: 'group',
        label: '复制链接后打开',
      },
    ],
  },
]

// 过滤菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    if (menu.key.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}
// 通过过滤菜单方法过滤用户不需要看到的菜单项
const items = computed<MenuProps['items']>(() => filterMenus(originItems))
</script>
<style scoped>
#globalHeader .title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
